<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

$product_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$product_id) {
    header('Location: index.php');
    exit();
}

$product = getProductById($pdo, $product_id);

if (!$product) {
    header('Location: index.php');
    exit();
}

$page_title = $product['name'];
?>
<?php include '../includes/header.php'; ?>

<main style="padding: 2rem 0;">
    <div class="container">
        <!-- Breadcrumb -->
        <div style="margin-bottom: 2rem;">
            <a href="/chuan/513i/" style="color: #7f8c8d;">Home</a> / 
            <a href="/chuan/513i/products/" style="color: #7f8c8d;">Products</a> / 
            <span style="color: #2c3e50;"><?php echo htmlspecialchars($product['name']); ?></span>
        </div>

        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 3rem; margin-bottom: 3rem;">
            <!-- Product Image -->
            <div>
                <div class="product-image" style="height: 400px; border-radius: 12px; overflow: hidden;">
                    <?php
                    // Try to resolve image from JSON by product name
                    $jsonPath = __DIR__ . '/../data/products.json';
                    $resolvedImage = '';
                    if (file_exists($jsonPath)) {
                        $jsonData = json_decode(file_get_contents($jsonPath), true);
                        if (is_array($jsonData)) {
                            foreach ($jsonData as $jp) {
                                if (isset($jp['name']) && $jp['name'] === $product['name']) {
                                    $candidate = $jp['image_url'] ?? '';
                                    if ($candidate && strpos($candidate, 'http') !== 0 && strpos($candidate, '/') !== 0) {
                                        $candidate = '../assets/images/' . rawurlencode(basename($candidate));
                                    }
                                    $resolvedImage = $candidate;
                                    break;
                                }
                            }
                        }
                    }
                    if (!$resolvedImage) {
                        $resolvedImage = 'https://images.unsplash.com/photo-1544947950-fa07a98d237f?w=400&h=300&fit=crop&crop=center';
                    }
                    ?>
                    <img src="<?php echo htmlspecialchars($resolvedImage); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>" style="width: 100%; height: 100%; object-fit: cover;">
                </div>
            </div>

            <!-- Product Info -->
            <div>
                <h1 style="margin-bottom: 1rem; color: #2c3e50;"><?php echo htmlspecialchars($product['name']); ?></h1>
                
                <?php if ($product['category_name']): ?>
                    <p style="color: #7f8c8d; margin-bottom: 1rem;">Category: <?php echo htmlspecialchars($product['category_name']); ?></p>
                <?php endif; ?>
                
                <div class="product-price" style="font-size: 2rem; margin-bottom: 2rem;">
                    <?php echo formatPrice($product['price']); ?>
                </div>
                
                <div style="margin-bottom: 2rem;">
                    <h3 style="margin-bottom: 1rem; color: #2c3e50;">Description</h3>
                    <p style="line-height: 1.6; color: #555;"><?php echo nl2br(htmlspecialchars($product['description'])); ?></p>
                </div>

                <!-- Stock Status -->
                <div style="margin-bottom: 2rem;">
                    <?php if ($product['stock_quantity'] > 0): ?>
                        <p style="color: #27ae60; font-weight: 500;">
                            <i class="fas fa-check-circle"></i> In Stock (<?php echo $product['stock_quantity']; ?> available)
                        </p>
                    <?php else: ?>
                        <p style="color: #e74c3c; font-weight: 500;">
                            <i class="fas fa-times-circle"></i> Out of Stock
                        </p>
                    <?php endif; ?>
                </div>

                <!-- Add to Cart Form -->
                <?php if ($product['stock_quantity'] > 0): ?>
                    <form id="add-to-cart-form" style="display: flex; gap: 1rem; align-items: center; margin-bottom: 2rem;">
                        <div style="display: flex; align-items: center; gap: 0.5rem;">
                            <label for="quantity">Quantity:</label>
                            <input type="number" id="quantity" name="quantity" value="1" min="1" max="<?php echo $product['stock_quantity']; ?>" 
                                   style="width: 80px; padding: 0.5rem; border: 2px solid #ecf0f1; border-radius: 5px;">
                        </div>
                        <button type="submit" class="btn btn-primary add-to-cart" data-product-id="<?php echo $product['id']; ?>">
                            <i class="fas fa-shopping-cart"></i> Add to Cart
                        </button>
                    </form>
                <?php else: ?>
                    <button class="btn btn-secondary" disabled>
                        <i class="fas fa-times"></i> Out of Stock
                    </button>
                <?php endif; ?>

                <!-- Product Features -->
                <div style="border-top: 1px solid #ecf0f1; padding-top: 2rem;">
                    <h3 style="margin-bottom: 1rem; color: #2c3e50;">Product Features</h3>
                    <ul style="list-style: none; padding: 0;">
                        <li style="margin-bottom: 0.5rem; color: #555;">
                            <i class="fas fa-check" style="color: #27ae60; margin-right: 0.5rem;"></i>
                            Hand-crafted with premium ingredients
                        </li>
                        <li style="margin-bottom: 0.5rem; color: #555;">
                            <i class="fas fa-check" style="color: #27ae60; margin-right: 0.5rem;"></i>
                            Eco-friendly and sustainable packaging
                        </li>
                        <li style="margin-bottom: 0.5rem; color: #555;">
                            <i class="fas fa-check" style="color: #27ae60; margin-right: 0.5rem;"></i>
                            Free shipping on orders over $100
                        </li>
                        <li style="margin-bottom: 0.5rem; color: #555;">
                            <i class="fas fa-check" style="color: #27ae60; margin-right: 0.5rem;"></i>
                            30-day satisfaction guarantee
                        </li>
                    </ul>
                </div>
            </div>
        </div>

        <!-- Related Products -->
        <div style="border-top: 1px solid #ecf0f1; padding-top: 3rem;">
            <h2 style="text-align: center; margin-bottom: 2rem; color: #2c3e50;">You Might Also Like</h2>
            
            <?php
            // Get related products (same category, excluding current product)
            // Check if category_id exists, otherwise use null to get all products
            $category_id = isset($product['category_id']) ? $product['category_id'] : null;
            
            if ($category_id) {
                $related_products = getProductsByCategory($pdo, $category_id, 4);
            } else {
                // If no category_id, get random products
                $related_products = getAllProducts($pdo, 4);
            }
            
            $related_products = array_filter($related_products, function($p) use ($product_id) {
                return $p['id'] != $product_id;
            });
            $related_products = array_slice($related_products, 0, 3);
            ?>
            
            <?php if (!empty($related_products)): ?>
                <div class="products-grid" style="grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));">
                    <?php foreach ($related_products as $related_product): ?>
                    <div class="product-card">
                        <div class="product-image">
                            <?php
                            // Resolve related product image from JSON
                            $relatedImage = '';
                            if (file_exists($jsonPath)) {
                                $jsonData = json_decode(file_get_contents($jsonPath), true);
                                if (is_array($jsonData)) {
                                    foreach ($jsonData as $jp) {
                                        if (isset($jp['name']) && $jp['name'] === $related_product['name']) {
                                            $candidate = $jp['image_url'] ?? '';
                                            if ($candidate && strpos($candidate, 'http') !== 0 && strpos($candidate, '/') !== 0) {
                                                $candidate = '../assets/images/' . rawurlencode(basename($candidate));
                                            }
                                            $relatedImage = $candidate;
                                            break;
                                        }
                                    }
                                }
                            }
                            if (!$relatedImage) {
                                $relatedImage = 'https://images.unsplash.com/photo-1544947950-fa07a98d237f?w=400&h=300&fit=crop&crop=center';
                            }
                            ?>
                            <img src="<?php echo htmlspecialchars($relatedImage); ?>" alt="<?php echo htmlspecialchars($related_product['name']); ?>">
                            <div class="product-overlay">
                                <a href="view.php?id=<?php echo $related_product['id']; ?>" class="btn btn-outline">View Details</a>
                            </div>
                        </div>
                        <div class="product-info">
                            <h3><?php echo htmlspecialchars($related_product['name']); ?></h3>
                            <p><?php echo htmlspecialchars(substr($related_product['description'], 0, 80)) . '...'; ?></p>
                            <div class="product-price"><?php echo formatPrice($related_product['price']); ?></div>
                            <a href="view.php?id=<?php echo $related_product['id']; ?>" class="btn btn-outline" style="width: 100%; text-align: center;">
                                View Details
                            </a>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</main>

<script>
// Handle add to cart form
document.getElementById('add-to-cart-form').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const quantity = document.getElementById('quantity').value;
    const productId = <?php echo $product['id']; ?>;
    
    addToCart(productId, parseInt(quantity));
});
</script>

<?php include '../includes/footer.php'; ?>
